package kmitl.comsci.bustacker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class SearchActivity extends Activity {

	final static int REQ_CODE = 1;
	
	private Spinner startSpinner;
	private Spinner endSpinner;
	
	private HttpPost httppost;
    private HttpClient httpclient;
    private List<NameValuePair> nameValuePairs;
    
    private String start_location = null;
    private String end_location = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);
		setButton();
		setSearchSpiner();
		
	}
	
	private void setButton() {
		Button nextbutton = (Button) findViewById(R.id.search_NextButton);
		nextbutton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(SearchActivity.this, SelectLineActivity.class);
				
				 //---- send data to next page
			     Bundle bundle = new Bundle();
			     bundle.putString("start_name",start_location);
			     bundle.putString("end_name", end_location);
			     intent.putExtras(bundle);
			     
			     startActivityForResult(intent,REQ_CODE );
			     finish();
			}
		});
		
		Button backButton = (Button) findViewById(R.id.search_BackButton);
		backButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(SearchActivity.this, HomeActivity.class);
				startActivity(intent);
				finish();
			}
		});
	}
	

	private void setSearchSpiner() {
		
		startSpinner = (Spinner)findViewById(R.id.select_FirstLocation);
		endSpinner = (Spinner)findViewById(R.id.select_EndLocation);
		
		JSONObject jObject = initTextList();
		
		List<String> arrList = new ArrayList<String>();
		
		try {
			arrList = getDataFromJson(jObject);
		} catch (IllegalStateException e) {
			
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		} catch (JSONException e) {
			
			e.printStackTrace();
		}
		
		ArrayAdapter<String> arrAd = new ArrayAdapter<String>(SearchActivity.this,
				android.R.layout.simple_spinner_item, 
				arrList);
		
		startSpinner.setAdapter(arrAd);
		endSpinner.setAdapter(arrAd);
		
		
		startSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
		    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		        Object item = parent.getItemAtPosition(pos);
		        start_location = item.toString();
		       
		    }
		    public void onNothingSelected(AdapterView<?> parent) {
		    	//someting
		    }
		});
		
		endSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
		    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		        Object item = parent.getItemAtPosition(pos);
		        end_location = item.toString();
		       
		    }
		    public void onNothingSelected(AdapterView<?> parent) {
		    	//someting
		    }
		});
		
	}
	private JSONObject initTextList() {
		
		//--StrictMode
		StrictMode.ThreadPolicy policy = new
				StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
				StrictMode.setThreadPolicy(policy);
	    
		//---connect to server	
		httpclient 		= new DefaultHttpClient();
		httppost 		= new HttpPost("http://161.246.13.242/itone/php_get_location_name.php");
		nameValuePairs  = new ArrayList<NameValuePair>();
		
		//-------------------------------------------------------------
		InputStream is = null;
        String result = null;
        JSONObject jsObj = null;
       
        try {
            
            httppost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
 
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
 
            is.close();
            result = sb.toString();
            
        
        } catch (ClientProtocolException e) {
            Log.e("ConnectServer", e.toString());
        } catch (IOException e) {
            Log.e("ConnectServer", e.toString());
        }
        
        try {
			jsObj =  new JSONObject(result);
		} catch (JSONException e) {
			
			e.printStackTrace();
		}
		
        return jsObj;
	}
	
	public ArrayList<String> getDataFromJson(JSONObject jsonObject)throws IllegalStateException,IOException, JSONException, NoSuchAlgorithmException 
	{
		ArrayList<String> busRoute = new ArrayList<String>();
		JSONArray array = jsonObject.getJSONArray("Location Name");		 
		 	 
		
		if(array!=null)
	    {	
			 
			 for(int i = 0; i<array.length(); i++) 
			 {
					busRoute.add(array.getJSONObject(i).getString("location_name"));
			 }
			 	
	      }
		
		return busRoute;
				
	}
}
